<template>
    <div class="tsPage page">
        <div class="header">
            <div class="toolbar">
                <div class="logo">
                    <div class="img">
                        <img :src="logoImg" alt="">
                    </div>
                    <div class="title">
                        <div class="master">{{athsInfo.eventName}}</div>
                        <div class="detail">{{athsInfo.phaseName}}</div>
                    </div>
                </div>

                <div class="lights">
                    <div :class="(tsInfo.lightW>0)?'W lig active':'W lig '"></div>
                    <div :class="(tsInfo.lightR>0)?'R lig active':'R lig '"></div>
                    <div :class="(tsInfo.lightG>0)?'G lig active':'G lig '"></div>
                    <div :class="(tsInfo.lightw>0)?'w lig active':'w lig '"></div>
                </div>

                <div class="acs">
                    <ul class="lstAcs">
                    
                        <li @click="acChangePos"><i class="fa fa-exchange"></i> <div class="txt">换边</div></li>
                        <li @click="acBack"><i class="fa fa-reply"></i> <div class="txt">返回</div></li>
                    </ul>
                </div>
            </div>
        </div>
        <div class="body">
            <div class="pannel">
                <div class="player">
                    <div class="athlete">
                        <el-button type="danger" ><i class="fa fa-flag"></i> 弃权</el-button>
                        <el-button  v-show="athsInfo.matchType =='TM'" type="warning"><i class="fa fa-flag"></i> 替补</el-button>
                        <div class="delegation">{{home.delegation}}</div>
                        <div class="name">{{home.name}}</div>
                    </div>
                    <div class="result">
                        <div class="score">{{tsInfo.homeScore}}</div>
                        <div class="flags">
                            <div :class="tsInfo.homeYello>0?'yello flag active':'yello flag'"></div>
                            <div :class="tsInfo.homeRed>0?'red flag active':'red flag'"></div>
                        </div>
                        <div v-show="tsInfo.homeWinFlag>0" class="winFlag">
                            <img :src="winFlagImg" alt="">
                        </div>
                    </div>
                </div>
                <div class="sets">

                    <div class="timeClock">{{tsInfo.currentTm}}</div>
                    <ul class="lstSets">
                        <li
                            v-for="(set,setIndex) in setCounts[athsInfo.matchType]"
                            :key="setIndex"
                            :class = "tsInfo.currentSet==set?'active':''"
                        >
                            <div class="setItem">
                               第 {{set}} 局
                            </div>
                        </li>
                    </ul>

                </div>
                <div class="player">
                    <div class="athlete">
                        <div class="delegation">{{away.name}}</div>
                        <div class="name">{{away.delegation}}</div>
                        <el-button v-show="athsInfo.matchType =='TM'" type="warning"><i class="fa fa-flag"></i> 替补</el-button>
                        <el-button type="danger" ><i class="fa fa-flag"></i> 弃权</el-button>
                    </div>
                    <div class="result">
                        <div class="score">{{tsInfo.awayScore}}</div>
                        <div class="flags">
                            <div :class="tsInfo.awayYello>0?'yello flag active':'yello flag'"></div>
                            <div :class="tsInfo.awayRed>0?'red flag active':'red flag'"></div>
                        </div>
                        <div v-show="tsInfo.awayWinFlag>0" class="winFlag">
                            <img :src="winFlagImg" alt="">
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import mqtt from 'mqtt'
class TMqClient {
  constructor () {
    this.config = {
      url: 'ws://192.168.0.248:10085/mqtt',
      uid: 'admin',
      pwd: 'public',
      autoSubTopics: []
    }
    this.options = {
      clientId: '',
      keepalive: 60,
      clean: true,
      reconnectPeriod: 1000,
      connectTimeout: 10000,
      username: '',
      password: ''
    }
    this.client = null
    this.clientId = ''
    this.onMessage = (topic, messageStr) => {}
  };

  open () {
    var me = this
    return new Promise((success, faild) => {
      try {
        me.close()
        var clientId = ['mid', (new Date()).getTime().toString()].join('')
        var options = JSON.parse(JSON.stringify(me.options))
        options.clientId = clientId
        options.username = me.config.uid
        options.password = me.config.pwd
        var client = mqtt.connect(me.config.url, options)
        client.on('connect', (e) => {
          console.log('mqclient is connected.')
          client.subscribe(me.config.autoSubTopics, (error) => {
            if (error && error != null) {
              console.log('subscribe faild.')
            } else {
              console.log('subscribe success.')
            }
          })
          me.client = client
          me.clientId = clientId
          success()
        })
        client.on('reconnect', (e) => {
          console.log('mqclient is reconnecting ...')
        })
        client.on('close', (e) => {
          console.log('mqclient is closed .')
        })
        client.on('error', (e) => {
          console.log('mqclient connect faild.')
        })
        client.on('message', (topic, message) => {
          console.log('recieve message. ', topic, message.toString())
          if (me.onMessage && me.onMessage != null) {
            try {
              me.onMessage(topic, message.toString())
            } catch (error) {
              console.log(error)
            }
          }
        })
      } catch (er) {
        console.log(er)
        success()
      }
    })
  };

  close () {
    var me = this
    try {
      if (me.client && me.client != null && me.client.connected) {
        me.client.end()
      }
      me.clientId = ''
      me.client = null
    } catch (er) {
      console.log(er)
    }
  };

  isConnected () {
    var me = this
    var res = false
    try {
      res = me.client && me.client != null && me.client.connected
    } catch (er) {
      console.log(er)
    }
    return res
  };
}
class TTsInfo {
  constructor () {
    this.tsCode = ''
    this.lightR = 0
    this.lightG = 0
    this.lightW = 0
    this.lightw = 0
    this.homeScore = 0
    this.homeYello = 0
    this.homeRed = 0
    this.homeWinFlag = 0
    this.awayScore = 0
    this.awayYello = 0
    this.awayRed = 0
    this.awayWinFlag = 0
    this.currentSet = 1
    this.currentTm = '03:00'
  }
}
const mqClient = new TMqClient()
export default {
  mounted () {
    var me = this
    try { 
      me.$nextTick().then(_=>{
        me.init()
        me.openMqClient()
      })
    } catch (er) {
      console.log(er)
    }
  },
  unmounted () {
    var me = this
    try { 
      mqClient.close();
    } catch (er) {
      console.log(er)
    }
  },
  data () {
    return {
      logoImg: require('../res/imgs/logo.png'),
      winFlagImg: require('../res/imgs/winFlag.jpg'),
      changePosFlag: 0,
      athsInfo: {},
      home: {},
      away: {},
      tsInfo: new TTsInfo(),
      sets: [],
      setCounts: {
        P: [1],
        IM: [1, 2, 3],
        TM: [1],
        TX: [1]
      },
      mqClient: new TMqClient(),
      lastDataMsg : null
    }
  },
  methods: {
    init () {
      var me = this
      try {
        me.tsInfo.tsCode = 'fets01'
        me.athsInfo = me.$route.query
        me.updateAthInfo()
        console.log(me.athsInfo)
      } catch (er) {
        console.log(er)
      }
    },
    openMqClient () {
      var me = this
      try {
        me.lastDataMsg = null;
        var flag = mqClient && mqClient != null ? mqClient.isConnected() : false
        if (!flag) {
          if (!(mqClient && mqClient != null)) {
            mqClient = new TMqClient()
          }
          mqClient.close()
          mqClient.onMessage = (topic, message) => {
            try {
              var flag = this.$route.path.indexOf('/tsInfo') > 0
              if (flag) {
                var msg = JSON.parse(message)
                console.log('recMessage', msg)
                if (msg.action && msg.action == 'data' && msg.Code == me.tsInfo.tsCode) {
                  me.updateTsInfoData(msg)
                  var info = me.getInfo();
                  var topic = "/fe2023/notify2SCB/"+me.tsInfo.tsCode;
                  var scbmsg = {
                    action:"updateData",
                    info:info
                  };
                  mqClient.client.publish(topic,JSON.stringify(scbmsg));
                  console.log('----------------', topic)
                  console.log(info);
                } else if (msg.action && msg.action == 'currentTime' && msg.Code == me.tsInfo.tsCode) { 
                  me.updateTsInfoTime(msg)
                  var topic = "/fe2023/notify2SCB/"+me.tsInfo.tsCode;
                  var scbmsg = {
                    action:"updateTM",
                    info:me.tsInfo.currentTm
                  };
                  mqClient.client.publish(topic,JSON.stringify(scbmsg));
                  console.log('----------------', topic)
                  console.log(scbmsg);
                }
              }
            } catch (error) {
              console.log(error)
            }
          }
          var dataTopic = ['/fe2023/ts', 'data', me.tsInfo.tsCode].join('/')
          var tmTopic = ['/fe2023/ts', 'time', me.tsInfo.tsCode].join('/')
          mqClient.config.autoSubTopics = [dataTopic, tmTopic]
          mqClient.open().then(_=>{
            var topic="/fe2023/query";
            var msg = {
              action:'query'
            };
            mqClient.client.publish(topic , JSON.stringify(msg));
            console.log(topic)
          })
        }
      } catch (er) {
        console.log(er)
      }
    },
    updateAthInfo () {
      var me = this
      try {
        me.home = me.changePosFlag > 0 ? {
          delegation: me.$route.query.AwayDelegation,
          name: me.$route.query.AwayName,
          position: me.$route.query.AwayPosition
        } : {
          delegation: me.$route.query.HomeDelegation,
          name: me.$route.query.HomeName,
          position: me.$route.query.HomePosition
        }
        me.away = me.changePosFlag > 0 ? {
          delegation: me.$route.query.HomeDelegation,
          name: me.$route.query.HomeName,
          position: me.$route.query.HomePosition
        } : {
          delegation: me.$route.query.AwayDelegation,
          name: me.$route.query.AwayName,
          position: me.$route.query.AwayPosition
        }
      } catch (er) {
        console.log(er)
      }
    },
    acChangePos () {
      var me = this
      try {
        me.changePosFlag = me.changePosFlag > 0 ? 0 : 1
        me.updateAthInfo();
                  var info = me.getInfo();
                  var topic = "/fe2023/notify2SCB/"+me.tsInfo.tsCode;
                  var scbmsg = {
                    action:"updateData",
                    info:info
                  };
                  mqClient.client.publish(topic,JSON.stringify(scbmsg));
                  console.log('----------------', topic)
                  console.log(info);
        /*
        if( me.lastDataMsg && me.lastDataMsg!=null){
          me.updateTsInfoData(me.lastDataMsg); 
        }
        */
      } catch (er) {
        console.log(er)
      }
    },
    acBack () {
      var me = this
      try {
        me.$router.back()
      } catch (er) {
        console.log(er)
      }
    },
    updateTsInfoData (msg) {
      var me = this
      try {
        me.lastDataMsg = msg;
        me.tsInfo.lightR = msg.LightRed
        me.tsInfo.lightR = msg.lightGreen
        me.tsInfo.lightW = msg.LightWhite
        me.tsInfo.lightw = msg.LightW
        me.tsInfo.currentTm = msg.CurrentTime
        me.tsInfo.currentSet = msg.SetIndex

      
          me.tsInfo.awayScore = msg.ScoreLeft
          me.tsInfo.awayYello = msg.FlagYelloLeft
          me.tsInfo.awayRed = msg.FlagRedLeft
          me.tsInfo.awayWinFlag = msg.WinFlag == 1 ? 1 : 0
          me.tsInfo.homeScore = msg.ScoreRight
          me.tsInfo.homeYello = msg.FlagYelloRight
          me.tsInfo.homeRed = msg.FlagRedRight
          me.tsInfo.homeWinFlag = msg.WinFlag == 2 ? 1 : 0

        /*
        if (me.changePosFlag > 0) {
          me.tsInfo.homeScore = msg.ScoreLeft
          me.tsInfo.homeYello = msg.FlagYelloLeft
          me.tsInfo.homeRed = msg.FlagRedLeft
          me.tsInfo.homeWinFlag = msg.WinFlag == 1 ? 1 : 0
          me.tsInfo.awayScore = msg.ScoreRight
          me.tsInfo.awayYello = msg.FlagYelloRight
          me.tsInfo.awayRed = msg.FlagRedRight
          me.tsInfo.awayWinFlag = msg.WinFlag == 2 ? 1 : 0
        } else {
          me.tsInfo.awayScore = msg.ScoreLeft
          me.tsInfo.awayYello = msg.FlagYelloLeft
          me.tsInfo.awayRed = msg.FlagRedLeft
          me.tsInfo.awayWinFlag = msg.WinFlag == 1 ? 1 : 0
          me.tsInfo.homeScore = msg.ScoreRight
          me.tsInfo.homeYello = msg.FlagYelloRight
          me.tsInfo.homeRed = msg.FlagRedRight
          me.tsInfo.homeWinFlag = msg.WinFlag == 2 ? 1 : 0
        }
        */
        
        var info = JSON.parse(JSON.stringify(me.tsInfo));
        me.tsInfo = info;
      } catch (er) {
        console.log(er)
      }
    },
    updateTsInfoTime (msg) {
      var me = this
      try {
        me.tsInfo.currentTm = msg.ct;
        /*
        var info = JSON.parse(JSON.stringify(me.tsInfo));
        info.currentTm = msg.ct;
        delete me.tsInfo["currentTm"];
        me.$set(me.tsInfo , 'currentTm' , msg.ct);
        me.$set()
        me.tsInfo={};
        me.tsInfo = info;
        me.$set(me.tsInfo, 'currentTm' , info.currentTm)
        */
        console.log('update tm',JSON.stringify(me.tsInfo))
      } catch (er) {
        console.log(er)
      }
    },
    getInfo () {
      var me = this;
      var info={};
      try {
        info.athsInfo = me.athsInfo;
        info.home = me.home;
        info.away = me.away;
        info.tsInfo = me.tsInfo;
      } catch (er) {
        console.log(er)
      }
      return info;
    }
  }

}
</script>

<style lang="less" scoped>
    @import url('./fe.less');
    .tsPage{
        background-color: #0b4383;
        color: #fff;
        display: flex;
        flex-direction: column;
        .header{
            padding: 20px;
            border-bottom: 5px solid #0077fe;
            .toolbar{
                display: flex;
                justify-content: space-between;
                align-items: center;
                .logo{
                    display: flex;
                    align-items: center;
                    .img{
                        height: 60px;
                        img{
                            height: 100%;
                            padding: 3px;
                            background-color: #fff;
                            border-radius: 2px;
                        }
                    }
                    .title{
                        padding-left: 10px;
                        .detail{
                            font-size: 1.2em;
                        }
                    }
                }
                .lights{
                    display: flex;
                    .lig{
                        margin: 0 10px;
                        width: 40px;
                        height: 40px;
                        border: 2px solid #fff;
                        border-radius: 50%;
                    }
                    .lig.R{
                        border: 2px solid #eb0c69;
                    }
                    .lig.R.active{
                        background-color:  #eb0c69;
                    }
                    .lig.G{
                        border: 2px solid rgb(22, 187, 17);
                    }
                    .lig.G.active{
                        background-color:  rgb(22, 187, 17);
                    }
                    .lig.W{
                        border: 2px solid #fafafa;
                    }
                    .lig.W.active{
                        background-color:  #fafafa;
                    }
                    .lig.w{

                        border: 2px solid #fafafa;
                    }
                    .lig.w.active{
                        background-color:  #fafafa;
                    }
                }
                .clockTime{
                    background-color: #eb0c69;
                    padding: 10px 0;
                    font-size: 2em;
                    font-weight: bold;
                    width: 120px;
                    text-align: center;
                    border-radius: 3px;
                }
                .acs{
                    ul.lstAcs{
                        display: flex;
                        li{
                            margin:0 10px;
                            background-color: #0077fe;
                            border-radius: 5px;
                            i{
                                height: 35px;
                                line-height: 40px;
                                width: 60px;
                                text-align: center;
                                font-size: 1.5em;
                            }
                            .txt{
                                height: 25px;
                                width: 60px;
                                text-align: center;
                            }
                        }
                        li:active{
                            background-color: #2b87f1;
                        }
                    }
                }
            }
        }
        .body{
            flex: 1;
            padding: 20px;
            .pannel{
                display: flex;
                height: 100%;
                .player{
                    width:43%;
                    height: 100%;
                    display: flex;
                    flex-direction: column;
                    .athlete{
                        margin-bottom: 15px;
                        padding: 15px;
                        background-color: #0077fe;
                        display: flex;
                        font-size: 2em;
                        justify-content: space-around;
                    }
                    .result{
                        position: relative;
                        flex: 1;
                        background-color: #0077fe;
                        .score{
                            height: 400px;
                            line-height: 400px;
                            text-align: center;
                            text-align: center;
                            font-weight: bold;
                            font-size: 25em;
                        }
                        .flags{
                            position: absolute;
                            bottom: 0;
                            display: flex;
                            left: 50%;
                            transform: translate(-50%);
                            .flag{
                                margin: 15px;
                                width: 40px;
                                height: 60px;
                            }
                            .flag.yello{
                                border:2px solid rgb(250, 234, 7);
                            }
                            .flag.yello.active{
                                background-color: rgb(250, 234, 7);
                            }
                            .flag.red{
                                border:2px solid #eb0c69;
                            }
                            .flag.red.active{
                                background-color: #eb0c69;
                            }
                        }
                        .winFlag{
                            position: absolute;
                            left: 20px;
                            bottom: 20px;
                            img{
                                width: 50px;
                                height: 50px;
                                border-radius: 10px;
                            }
                        }
                    }
                }
                .sets{
                    flex: 1;
                    position: relative;

                    .timeClock{
                        background-color: #eb0c69;
                        margin: 0 auto;
                        height:70px;
                        line-height:70px;
                        font-size: 2em;
                        font-weight: bold;
                        width: 120px;
                        text-align: center;
                        border-radius: 3px;
                    }
                    ul.lstSets{
                        position: absolute;
                        left:50%;
                        top:50%;
                        transform: translate(-50%, -50%);
                        li{
                            .setItem{
                                height: 40px;
                                line-height: 40px;
                                margin: 10px;
                                border:1px solid #fff;
                                width: 90px;
                                text-align: center;
                                border-radius: 3px;
                                font-weight: 2.5em;
                                font-weight: bold;
                            }
                        }
                        li.active .setItem{
                            background-color: #eb0c69;
                        }
                    }
                }
            }
        }
    }
</style>
